package scau.gsmg.misp.dao.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Set;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.ICustomerDAO;
import scau.gsmg.misp.vo.Member;
import scau.gsmg.misp.vo.Role;

/**
 * @Title 管理员对顾客的所有操作
 * @Group gaoshenmegui
 * @author ZCL
 * @date 2015年4月4日
 */

@Repository
public class CustomerDAO extends BaseDAO implements ICustomerDAO {

	/**
	 * 从第几页获取，每页显示几行获取会员信息
	 */
	@Override
	public List getCustomerList(String page, String rows, String sort,
			String order) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Member m";
		hql = hql + " order by " + sort + " " + order;
		List dataList = new ArrayList();
		try {
			// 当为缺省值的时候进行赋值
			int currentpage = Integer
					.parseInt((page == null || page == "0") ? "1" : page);// 第几页
			int pagesize = Integer
					.parseInt((rows == null || rows == "0") ? "10" : rows);// 每页多少行
			Query query = session.createQuery(hql);
			List<Member> customer = query
					.setFirstResult((currentpage - 1) * pagesize)
					.setMaxResults(pagesize).list();
			for (Member m : customer) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", m.getId());
				jsonMap.put("name", m.getName());
				jsonMap.put("gender", m.getGender());
				jsonMap.put("cellphone", m.getCellphone());
				jsonMap.put("address", m.getAddress());
				jsonMap.put("discount", m.getDiscount());
				jsonMap.put("integral", m.getIntegral());
				jsonMap.put("createTime", m.getCreateTime());
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return null;

	}

	/**
	 * 添加新会员
	 */
	@Override
	public boolean addCustomer(String name, String gender, String cellphone,
			String address, double discount, int integral) throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		// 插入当前时间
		Date date = new Date();
		String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(date);// 将时间格式转换成符合Timestamp要求的格式
		Timestamp time = Timestamp.valueOf(nowTime);

		Session session = getSession();
		try {
			Member newMember = new Member(name, gender, cellphone, address,
					discount, integral, time, null);
			Transaction tx = session.beginTransaction();
			session.save(newMember);
			tx.commit();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 修改会员信息
	 */
	@Override
	public boolean editCustomer(int id, String name, String gender,
			String cellphone, String address, double discount, int integral)
			throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {
			String hql = "update Member m set m.name=?,m.gender=?,m.cellphone=?,m.address=?,m.discount=?,m.integral=? where m.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, name);
			query.setParameter(1, gender);
			query.setParameter(2, cellphone);
			query.setParameter(3, address);
			query.setParameter(4, discount);
			query.setParameter(5, integral);
			query.setParameter(6, id);
			query.executeUpdate();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 删除会员
	 */
	@Override
	public boolean removeCustomer(int id) throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {
			String hql = "delete Member m where m.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.executeUpdate();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 搜索会员
	 */
	@Override
	public List searchCustomer(String page, String rows, int id, String name,
			String cellphone, String sort, String order) throws Exception {
		// TODO Auto-generated method stub
		List dataList = new ArrayList();
		Session session = getSession();
		String hql = "from Member m";
		if (id > 0) {
			hql = hql + " where m.id=" + id;
		}
		if (name != null) {
			// hql=hql+" where m.name like " +"'%"+name+"%'";
			hql = hql + " where m.name like ?";
		}
		if (cellphone != null) {
			hql = hql + " where m.cellphone=" + cellphone;
		}
		hql = hql + " order by " + sort + " " + order;
		try {
			// 当为缺省值的时候进行赋值
			int currentpage = Integer
					.parseInt((page == null || page == "0") ? "1" : page);// 第几页
			int pagesize = Integer
					.parseInt((rows == null || rows == "0") ? "10" : rows);// 每页多少行
			Query query = session.createQuery(hql);
			if (name != null) {
				query.setParameter(0, "%" + name + "%");
			}

			List<Member> customer = query
					.setFirstResult((currentpage - 1) * pagesize)
					.setMaxResults(pagesize).list();
			for (Member m : customer) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", m.getId());
				jsonMap.put("name", m.getName());
				jsonMap.put("gender", m.getGender());
				jsonMap.put("cellphone", m.getCellphone());
				jsonMap.put("address", m.getAddress());
				jsonMap.put("discount", m.getDiscount());
				jsonMap.put("integral", m.getIntegral());
				jsonMap.put("createTime", m.getCreateTime());
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 通过日期区间搜索会员
	 */
	@Override
	public List searchByDate(Date firstDate, Date lastDate, String page,
			String rows, String sort, String order) throws Exception {
		// TODO Auto-generated method stub
		List dataList = new ArrayList();
		Session session = getSession();
		// 把日期推迟一天才能查到包含最后一天在内的记录
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(lastDate);
		calendar.add(calendar.DATE, 1); // 把日期往后增加一天
		lastDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
		// String
		// hql="from Member m where m.createTime >= ? and m.createTime <= ?";
		String hql = "from Member m where m.createTime between ? and ?";
		hql = hql + " order by " + sort + " " + order;
		try {
			// 当为缺省值的时候进行赋值
			int currentpage = Integer
					.parseInt((page == null || page == "0") ? "1" : page);// 第几页
			int pagesize = Integer
					.parseInt((rows == null || rows == "0") ? "10" : rows);// 每页多少行
			Query query = session.createQuery(hql);
			query.setParameter(0, firstDate);
			query.setParameter(1, lastDate);
			List<Member> customer = query
					.setFirstResult((currentpage - 1) * pagesize)
					.setMaxResults(pagesize).list();
			for (Member m : customer) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", m.getId());
				jsonMap.put("name", m.getName());
				jsonMap.put("gender", m.getGender());
				jsonMap.put("cellphone", m.getCellphone());
				jsonMap.put("address", m.getAddress());
				jsonMap.put("discount", m.getDiscount());
				jsonMap.put("integral", m.getIntegral());
				jsonMap.put("createTime", m.getCreateTime());
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 统计记录数
	 */
	@Override
	public int CountRecords(String hql, Object[] parameters) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			Query query = session.createQuery(hql);
			if (parameters != null) {
				for (int i = 0; i < parameters.length; i++) {
					query.setParameter(i, parameters[i]);
				}
			}
			List customer = query.list();
			int size = customer.size();
			return size;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return 0;
	}

}
